package com.power.flowable.controller;

import com.power.flowable.api.IProcessDefFeign;
import feign.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
public class ProcessDefController {

    @Resource
    private IProcessDefFeign iProcessDefFeign;


    @GetMapping("/flow/viewCharUnpublishedDiagram")
    public void viewCharUnpublishedDiagram(HttpServletResponse response, @RequestParam(name = "modelKey", required = true) String modelKey) throws IOException {

        Response rep = iProcessDefFeign.viewUnpublishedDiagram(modelKey);

        Response.Body body = rep.body();
        InputStream in = body.asInputStream();

        OutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }

    @GetMapping("/flow/viewCharDiagram")
    public void viewCharDiagram(HttpServletResponse response, @RequestParam(name = "processdefinitionid", required = true) String processdefinitionid) throws Exception {

        Response rep = iProcessDefFeign.viewDiagram(processdefinitionid);

        Response.Body body = rep.body();
        InputStream in = body.asInputStream();

        OutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
